#!/usr/bin/env python
# -*- coding:utf-8 -*-

from models.sys_admin import SysAdmin
from utils.rsa_encryption_decryption import RSAEncryptionDecryption
from utils.jwt_util import JwtToken
from config import Config
from controller.sysAdminController import SysAdminController
class SysAdminService:
    @staticmethod
    def login(account, password):
        """用户登录服务"""
        try:
            # 1. 查询用户
            admin =SysAdminController.get(account=account)
            if not admin:
                return {"code": "4001", "message": "用户不存在"}

            # 2. 解密前端传来的密码
            decrypted_password = RSAEncryptionDecryption.decrypt(password)
            if decrypted_password is None:
                return {"code": "4002", "message": "密码解密失败"}

            # 3. 验证密码
            if admin['data'][0]['password'] != decrypted_password:
                return {"code": "4002", "message": "密码错误"}

            # 4. 生成token数据
            token_data = {
                "user_id": admin['data'][0]['user_id'],
                "user_type": 0,  # 0表示系统管理员
                "account": admin['data'][0]['account']
            }

            # 5. 获取JWT配置
            jwt_config = Config.get_jwt_config()

            # 6. 生成token
            token = JwtToken.generate_token(
                data=token_data,
                secret_key=jwt_config['secret_key'],
                expires_in=jwt_config['token_expires']
            )
            # 7. 返回用户信息和token
            return {
                "code": "2000",
                "message": "登录成功",
                "data": {
                    "user_id": admin['data'][0]['user_id'],
                    "name": admin['data'][0]['name'],
                    "account": admin['data'][0]['account'],
                    "token": token
                }
            }

        except Exception as e:
            print(f"Login error: {str(e)}")  # 实际应该使用logger
            return {
                "code": "5000",
                "message": "服务器内部错误",
                "error": str(e)
            }

    @staticmethod
    def update_password(user_id, old_password, new_password):
        """修改密码服务"""
        # 业务逻辑处理
        pass
